//
//  MeViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/6/22.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "MeViewController.h"
#import "ArtGalleryViewController.h"
#import "FriendViewController.h"
#import "FansViewController.h"
#import "MessageViewController.h"
#import "PersonalDataVCtrol.h"
#import "MyOrdersViewController.h"
#import "SettingsViewController.h"
#import "MyBuyViewController.h"
#import "WalletViewController.h"
#import "PhotoUpLoadAgreementViewController.h"
#import "MeViewBtnCell.h"
#import "PhoneNumViewController.h"
#import "IGGetMyinfoApi.h"
#import "IGUserInfo.h"
#import "MyGoodsViewController.h"
#import "IntroViewController.h"
#import "IGMyiGalleryVC.h"
#import "IGCreatPictureListVC.h"
#import "IGPictureListDetailVC.h"
#import "IGMultipleDrawingsBuyVC.h"
#import "IGExhibitionVC.h"
#import "XiangQingViewController.h"
#import "IGPushiGalleryListVC.h"
#import "IGCompetitionVC.h"
#import "IGMyPaintingListManagerVC.h"
#import "IGEditPictureListVC.h"
#import "IGPictureListDetailVC.h"
#import "IGLinkiGalleryBluetoothVC.h"

@interface MeViewController () <UITableViewDelegate, UITableViewDataSource> {
    UIView *header;
    UIImageView *shadowImageView;
    NSInteger userSelectedChannelID;
    
    UIView *statusBarView;
    UIImageView *background;
    UIImageView *icon;
    UILabel *name;
    
    UIImageView *red;
    UILabel *line;
    
    UITableViewCell *userCell;
    UIButton *canBtn;
    NSString *klanguage ;
}

@property (weak, nonatomic) IBOutlet UITableView *table;
@property(nonatomic,strong)IGGetMyinfoApi *meApi;
@property(nonatomic,strong)IGUserInfo *meinfoModel;

@end
//[[NSNotificationCenter defaultCenter] postNotificationName:@"MessageNotificationKey" object:userInfo];
@implementation MeViewController
#pragma mark -懒加载
-(IGUserInfo *)meinfoModel{
    if (!_meinfoModel) {
        _meinfoModel=[[IGUserInfo alloc]init];
    }
    return _meinfoModel;
}
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isNavgationBarHidden = YES;
    self.table.backgroundColor =[UIColor c2Color];
    
    statusBarView = [[UIView alloc]   initWithFrame:CGRectMake(0, -20,  self.view.bounds.size.width, 20)];
    statusBarView.backgroundColor = [UIColor whiteColor];
    [self.table addSubview:statusBarView];
    klanguage = [[NSUserDefaults standardUserDefaults] objectForKey:KLanguage];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage) name:@"MessageNotificationKey" object:nil];
    header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, INTROHEIGHT+33)];
    header.backgroundColor=[UIColor whiteColor];
    background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, INTROHEIGHT)];
    background.contentMode = UIViewContentModeScaleAspectFill;
    background.clipsToBounds = YES;
    [background setUserInteractionEnabled:YES];
    [header addSubview:background];
    //头像
    icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,GSCALE(70), GSCALE(70))];
    [icon sd_setImageWithURL:[NSURL URLWithString:[IGUser getImage]] placeholderImage:[UIImage imageNamed:@"place_head_Icon"]];
    icon.contentMode = UIViewContentModeScaleAspectFill;
    icon.layer.borderWidth = 1;
    icon.layer.borderColor = [UIColor whiteColor].CGColor;
    icon.layer.cornerRadius = icon.width/2;
    icon.layer.masksToBounds = YES;
    icon.y = (background.height-icon.height-name.height-10)/2+15;
    icon.centerX = background.width/2;
    UITapGestureRecognizer *iconTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconClick)];
    [icon addGestureRecognizer:iconTap];
    [icon setUserInteractionEnabled:YES];
     [background addSubview:icon];
    //昵称
    name = [[UILabel alloc] initWithFrame:CGRectZero];
//    name.text = @"用户昵称";
    name.text = NSLocalizedString(@"User Nickname", nil);
    name.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
    name.textColor = [UIColor c4Color];
    name.textAlignment=NSTextAlignmentCenter;
    [name sizeToFit];
    name.width = KSCREENWIDTH - 20;
    name.y = icon.bottom+8;
    name.centerX =icon.centerX;
    [background addSubview:name];
    //消息
    UIButton *messageBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [messageBtn setImage:[UIImage imageNamed:@"me-mail"] forState:UIControlStateNormal];
    [messageBtn setImage:[UIImage imageNamed:@"me-mail"] forState:UIControlStateSelected];
    messageBtn.frame=CGRectMake(KSCREENWIDTH-55, SafeTopMagin, 45, 45);
    [messageBtn addTarget:self action:@selector(messageBtn:) forControlEvents:UIControlEventTouchUpInside];
    //消息的红点
    UIImageView *redImgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"me-badge"]];
    redImgView.frame=CGRectMake(messageBtn.width/2, messageBtn.width/5, 15, 15);
    redImgView.hidden = YES;
    red=redImgView;
    [messageBtn addSubview:redImgView];
    [header addSubview:messageBtn];
    
    //我的关注button
    NSString *title1 = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"My Follow", nil),@"0"];
    NSString *title2 = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"My Follower", nil),@"0"];
    //    NSArray *title = @[@"我的关注 0", @"关注我的 0"];
    NSArray *title = @[title1,title2];
    for (int i=0; i<2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(KSCREENWIDTH/2*i, header.height-44, KSCREENWIDTH/2, 44)];
        [button setTag:i+100];
        [button setTitle:title[i] forState:UIControlStateNormal];
        if (i==0) {
            button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
            button.contentEdgeInsets=UIEdgeInsetsMake(0, 0, 0, 20);
        }else if (i==1){
            button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
            button.contentEdgeInsets=UIEdgeInsetsMake(0, 20, 0, 0);
        }
        button.titleLabel.font = [UIFont font12];
        [button setTitleColor:[UIColor c5Color] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor c5Color] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectNameButton:) forControlEvents:UIControlEventTouchUpInside];
        //我的关注&关注我的之间竖线
        line=[[UILabel alloc]initWithFrame:CGRectZero];
        line.backgroundColor=[UIColor c5Color];
        [line setFrame:CGRectMake(KSCREENWIDTH/2, 0, 1, GSCALE(20))];
        line.centerY=button.centerY;
        line.alpha=0.6;
        [header addSubview:button];
        [header addSubview:line];
        
    }
    self.table.y = -SafeTopMagin;
    self.table.h += SafeTopMagin;
    self.table.tableHeaderView = header;
    [self.table registerClass:[MeViewBtnCell class] forCellReuseIdentifier:@"MeViewBtnCell"];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self loadUserinfoData];
}
#pragma mark--获取用户数据
-(void)loadUserinfoData{//加载数据
    self.meApi = [IGGetMyinfoApi new];
    [self.meApi startWithDecodeClass:[IGGetMyinfoResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGGetMyinfoResp *resp=responseObject;
            IGGetMyinfoModel *model=resp.data;
            IGUserInfo *userInfo = model.member;
            [IGUser saveUserInfo:userInfo];
            self.meinfoModel = userInfo;
            [self updateUI];
            [self.table reloadData];
        }
    }];
}

- (void)updateUI{
    [icon sd_setImageWithURL:[NSURL URLWithString:self.meinfoModel.image] placeholderImage:[UIImage imageNamed:@"place_head_Icon"]];
    UITapGestureRecognizer *iconTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconClick)];
    [icon addGestureRecognizer:iconTap];
    icon.userInteractionEnabled=YES;
    name.text = self.meinfoModel.nike;
    UIButton *btn1 = [header viewWithTag:100];
    UIButton *btn2 = [header viewWithTag:101];
//    NSString *title1 = [NSString stringWithFormat:@"我的关注 %@",self.meinfoModel.focusNums.length>0?self.meinfoModel.focusNums:@"0"];
//    NSString *title2 = [NSString stringWithFormat:@"关注我的 %@", self.meinfoModel.followNums.length>0?self.meinfoModel.followNums:@"0"];
    NSString *title1 = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"My Follow", nil),self.meinfoModel.focusNums.length>0?self.meinfoModel.focusNums:@"0"];
    NSString *title2 = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"My Follower", nil),self.meinfoModel.followNums.length>0?self.meinfoModel.followNums:@"0"];
    [btn1 setTitle:title1 forState:UIControlStateNormal];
    [btn2 setTitle:title2 forState:UIControlStateNormal];
    
    if ([self.meinfoModel.unReadTotal integerValue]>0) {
        red.hidden = NO;
    } else {
        red.hidden = YES;
    }
}
- (void)receiveMessage{//收到消息后显示红点
    red.hidden = NO;
}
#pragma mark-Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 12;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return 3;
    } else if (section == 3) {
        return 1;
    }else if (section == 4) {
        return 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.separatorInset = UIEdgeInsetsMake(0, 45, 0, 0);
    cell.textLabel.font = [UIFont font16];
    cell.detailTextLabel.font = [UIFont font12];
    cell.textLabel.textColor=[UIColor c4Color];
    cell.textLabel.textAlignment=NSTextAlignmentLeft;
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    img.center = CGPointMake(25, 55/2);
    img.contentMode = UIViewContentModeScaleAspectFit;
    if (indexPath.section==0) {
//        MeViewBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeViewBtnCell" forIndexPath:indexPath];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.model = self.meinfoModel;
//        return cell;
        cell.textLabel.text = @"我的设备";
        img.image=[UIImage imageNamed:@"iGallery_Bind_Slave1"];
        [cell.contentView addSubview:img];
    }
    if (indexPath.section==1) {
        if ([canBtn isSelected] || [IGUser getTel].length != 0) {
            cell.hidden=YES;
        }else{
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType=UITableViewCellAccessoryNone;
            cell.textLabel.font=[UIFont font14];
            userCell=cell;
            cell.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0);
            cell.backgroundColor=RGB(220, 237, 246);
//            cell.textLabel.text=@"绑定手机账号更安全,请点击绑定";
            cell.textLabel.text=NSLocalizedString(@"Link your account with mobile for secured service. link now.", nil);
            cell.textLabel.adjustsFontSizeToFitWidth = YES;
            cell.textLabel.textAlignment=NSTextAlignmentLeft;
            cell.accessoryType=UITableViewCellAccessoryNone;
            UIButton *cancelBtn=[[UIButton alloc]initWithFrame:CGRectMake(KSCREENWIDTH-45,1, 35, 35)];
            [cancelBtn setImage:[UIImage imageNamed:@"cross" ] forState:UIControlStateNormal];
            canBtn=cancelBtn;
            [cell addSubview:cancelBtn];
            [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    if (indexPath.section==2) {
        if (indexPath.row==0) {
//            cell.textLabel.text = @"我的订单";
            cell.textLabel.text = NSLocalizedString(@"My Order", nil);
            img.image=[UIImage imageNamed:@"my_adress"];
            [cell.contentView addSubview:img];
        } else if (indexPath.row==1) {
            if ([self.meinfoModel.authens integerValue] != 2) {
                cell.hidden=YES;
            }
            if([klanguage containsString:@"en"]){
                cell.hidden=YES;
            }
            cell.textLabel.text = NSLocalizedString(@"My Item(s)", nil);
            img.image=[UIImage imageNamed:@"my_sale"];
            [cell.contentView addSubview:img];
        }else if (indexPath.row==2) {
//            cell.textLabel.text = @"钱包";
            cell.textLabel.text = NSLocalizedString(@"Wallet", nil);
             img.image=[UIImage imageNamed:@"my_wallet"];
            [cell.contentView addSubview:img];
        }
    } else if (indexPath.section==3) {
        if (indexPath.row==0) {
//            cell.textLabel.text = @"个人资料";
            cell.textLabel.text = NSLocalizedString(@"Profile", nil);
            if ([self.meinfoModel.authens integerValue] == 1){
//                cell.detailTextLabel.text=@"未认证";
                cell.detailTextLabel.text=NSLocalizedString(@"Unverified", nil);
            }else if ([self.meinfoModel.authens integerValue]==3){
//                cell.detailTextLabel.text=@"待认证";
                cell.detailTextLabel.text=NSLocalizedString(@"To be Verified", nil);
            }else if ([self.meinfoModel.authens integerValue]==2){
//                cell.detailTextLabel.text=@"通过";
                cell.detailTextLabel.text=NSLocalizedString(@"Passed", nil);
            }else if ([self.meinfoModel.authens integerValue]==4){
//                cell.detailTextLabel.text=@"未通过";
                cell.detailTextLabel.text=NSLocalizedString(@"Rejected", nil);
            }
            img.image=[UIImage imageNamed:@"my_profile"];
            [cell.contentView addSubview:img];
        }
    } else if (indexPath.section==4) {
//        cell.textLabel.text = @"设置";
        cell.textLabel.text = NSLocalizedString(@"Setting", nil);
        img.image=[UIImage imageNamed:@"my_set"];
        [cell.contentView addSubview:img];
    } else if(indexPath.section == 5){
        cell.textLabel.text = @"限量收藏";
    } else if (indexPath.section == 6){
        cell.textLabel.text = @"活动展览";
    } else if (indexPath.section == 7){
        cell.textLabel.text = @"画作详情";
    } else if (indexPath.section == 8){
        cell.textLabel.text = @"画作/画单推送";
    } else if (indexPath.section == 9){
        cell.textLabel.text = @"活动比赛";
    } else if (indexPath.section == 10){
        cell.textLabel.text = @"我的画单管理";
    } else if (indexPath.section == 11){
        cell.textLabel.text = @"蓝牙绑定设备";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
         [UIViewController ig_pushViewControllerClass:[IGMyiGalleryVC class] animated:YES];
    }
    if (indexPath.section==1) {
        PhoneNumViewController *phoneVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PhoneNumViewController"];
        [UIViewController ig_pushViewController:phoneVC animated:YES];
    }
    if (indexPath.section==2) {
        if (indexPath.row==0) { // 我的订单
            [UIViewController ig_pushViewControllerClass:[MyOrdersViewController class] animated:YES];
        } else if (indexPath.row==1) {//我的商品
            [UIViewController ig_pushViewControllerClass:[MyGoodsViewController class] animated:YES];
        }else if (indexPath.row==2) {//钱包
            [UIViewController ig_pushViewControllerClass:[WalletViewController class] animated:YES];
        }
    } else if (indexPath.section==3) {
        if (indexPath.row==0) { //  个人资料
            [UIViewController ig_pushViewControllerClass:[PersonalDataVCtrol class] animated:YES];
        }
    } else if (indexPath.section==4) {  // 设置
        [UIViewController ig_pushViewControllerClass:[SettingsViewController class] animated:YES];
    } else if (indexPath.section == 5){
        [UIViewController ig_pushViewControllerClass:[IGMultipleDrawingsBuyVC class] animated:YES];
    } else if (indexPath.section == 6){
        [UIViewController ig_pushViewControllerClass:[IGExhibitionVC class] animated:YES];
    } else if (indexPath.section == 7){
        [UIViewController ig_pushViewControllerClass:[XiangQingViewController class] animated:YES];
    } else if (indexPath.section == 8){
        [UIViewController ig_pushViewControllerClass:[IGPushiGalleryListVC class] animated:YES];
    } else if (indexPath.section == 9){
        [UIViewController ig_pushViewControllerClass:[IGCompetitionVC class] animated:YES];
    } else if (indexPath.section == 10){
        [UIViewController ig_pushViewControllerClass:[IGMyPaintingListManagerVC class] animated:YES];
    } else if (indexPath.section == 11){
        [UIViewController ig_pushViewControllerClass:[IGLinkiGalleryBluetoothVC class] animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==1 && ([canBtn isSelected] || [IGUser getTel].length != 0)) {
        return .01f;
    }
  
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(indexPath.section==0){
//        return INTROHEIGHT;
//    } else
        if (indexPath.section==1){
        if ([canBtn isSelected] || [IGUser getTel].length != 0) {
            return 0.01f;
        } else {
            return 36;
        }
    }else if (indexPath.section==2){
        if (indexPath.row==1) {
            if ([self.meinfoModel.authens integerValue]!=2) {
                return 0.001f;
            }
            if([klanguage containsString:@"en"]){
                return 0.001f;
            }
        }
    }
    return 55;
}
#pragma mark-取消显示绑定手机号cell
-(void)cancelBtnClick:(UIButton *)btn{
    [canBtn setSelected:YES];
    [_table reloadData];
}
#pragma mark-跳转我的关注,我的粉丝
- (void)selectNameButton:(UIButton *)sender {
    //如果更换按钮
    if (sender.tag != userSelectedChannelID) {
        //取之前的按钮
        UIButton *lastButton = (UIButton *)[header viewWithTag:userSelectedChannelID];
        if (userSelectedChannelID) {
            lastButton.selected = NO;
        }
        //赋值按钮ID
        userSelectedChannelID = sender.tag;
    }
    
    //按钮选中状态
    if (!sender.selected) {
        sender.selected = YES;
        
        [UIView animateWithDuration:0.25 animations:^{
            shadowImageView.centerX = sender.centerX;
        }];
    }
    if (sender.tag-100 == 0) { //  关注
        [UIViewController ig_pushViewControllerClass:[FriendViewController class] animated:YES];
    } else if (sender.tag-100 == 1) { // 粉丝
        [UIViewController ig_pushViewControllerClass:[FansViewController class] animated:YES];
    }
}
#pragma mark-跳转消息中心界面
-(void)messageBtn:(UIButton *)btn{
    [UIViewController ig_pushViewControllerClass:[MessageViewController class] animated:YES];
}
#pragma mark--点击头像跳转
-(void)iconClick{
    IntroViewController *vc=[[IntroViewController alloc]init];
    vc.u_id=self.meinfoModel.uid;
    [UIViewController ig_pushViewController:vc animated:YES];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
